﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SPSolutions.Samples.PickerApp
{
    /// <summary>
    /// Represent a city collection
    /// </summary>
	public class CityCollection : List<City>
	{
        /// <summary>
        /// Get the city
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public City GetCityNoThrow(string name)
        {
            foreach (City city in this)
            {
                if (city.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return city;
                }
            }
            return null;
        }

        /// <summary>
        /// Get the city by the accessor
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public City this[string name]
        {
            get
            {
                // Get the city
                City city = GetCityNoThrow(name);

                // No city found
                if (city == null)
                {
                    throw new ArgumentOutOfRangeException("name");
                }

                // Return the city
                return city;
            }
        }

        /// <summary>
        /// True if the city exists in the list
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Contains(string name)
        {
            return (GetCityNoThrow(name) != null);
        }

        /// <summary>
        /// Get a list of matching cities
        /// </summary>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public City[] GetMatchingCities(string pattern)
        {
            // No search provided
            if (string.IsNullOrEmpty(pattern))
            {
                return new City[0];
            }

            // Create a list of cities
            List<City> cities = new List<City>();

            // Find matching cities
            foreach (City city in this)
            {
                // No city name
                if(city.Name == null)
                {
                    continue;
                }

                // Found matching city
                if (Regex.IsMatch(city.Name, pattern, RegexOptions.IgnoreCase))
                {
                    cities.Add(city);
                }
            }

            // Return cities array
            return cities.ToArray();
        }
	}
}
